package com.example.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.reggie.common.Result;
import com.example.reggie.entity.Employee;
import com.example.reggie.service.EmployeeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;

@Slf4j
@RestController
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeService employeeService;

    /**
     * 员工登录
     *
     * @param request
     * @param employee
     * @return
     */
    @PostMapping("/login")
    public Result<Employee> login(HttpServletRequest request, @RequestBody Employee employee) {
        //1.将提交的密码做 md5 加密处理
        String psw = employee.getPassword();
        psw = DigestUtils.md5DigestAsHex(psw.getBytes());

        //2.如果没有查询到则返回d登录失败结果
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Employee::getUsername, employee.getUsername());
        Employee emp = employeeService.getOne(queryWrapper);

        //3.密码比对，如果不一致则返回登录失败结果
        if (emp == null) {
            return Result.error("账号不存在！");
        }

        //4.密码比对
        if (!emp.getPassword().equals(psw)) {
            return Result.error("密码错误！");
        }

        //5.查看员工状态，如果为已禁用状态，则返回员工已经禁用结果
        if (emp.getStatus() == 0) {
            return Result.error("此账号已被冻结！");
        }

        //6.登录成功，将员工ID存入Seesion并返回登录成功结果
        request.getSession().setAttribute("employee", emp.getId());

        return Result.success(emp);
    }

    ;

    @PostMapping("/logout")
    public Result<String> logOut(HttpServletRequest request) {

        request.getSession().removeAttribute("employee");
        return Result.success("登出成功");
    }

    ;

    /**
     * 新增员工
     *
     * @param employee
     * @return
     */
    @PostMapping
    public Result<String> save(HttpServletRequest request, @RequestBody Employee employee) {

        log.info("新增员工，员工信息:{}", employee.toString());

        //设置初始密码，使用 md5 加密
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

//        employee.setCreateTime(LocalDateTime.now());
//        employee.setUpdateTime(LocalDateTime.now());

        //获得当前登录用户的Id
//        Long empId = (Long) request.getSession().getAttribute("employee");
//        employee.setCreateUser(empId);
//        employee.setUpdateUser(empId);

//        存数据进入数据库
        employeeService.save(employee);


        return Result.success("新增员工成功！");
    }

    ;

    /**
     * 员工信息的分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public Result<Page<Employee>> page(int page, int pageSize, String name) {
        log.info("page:{},pageSize:{},name:{}", page, pageSize, name);
        // 构造分页构造器
        Page<Employee> pageInfo = new Page<Employee>(page, pageSize);
        // 构造条件构造器
        LambdaQueryWrapper<Employee> queryWrapper = new LambdaQueryWrapper<>();
        // 添加过滤条件
        queryWrapper.like(StringUtils.isNotEmpty(name), Employee::getName, name);
        // 添加排序条件
        queryWrapper.orderByDesc(Employee::getUpdateTime);
        // 执行查询
        employeeService.page(pageInfo, queryWrapper);
        return Result.success(pageInfo);
    }


    /**
     * 根据 ID 来修改员工信息
     *
     * @param employee
     * @return
     */
    @PutMapping
    public Result<String> update(HttpServletRequest request, @RequestBody Employee employee) {

        log.info(employee.toString());

        employee.setUpdateTime(LocalDateTime.now());
        employee.setUpdateUser((Long) request.getSession().getAttribute("employee"));

//        更新数据库表
        employeeService.updateById(employee);
        return Result.success("员工信息修改成功！");
    }

    ;

    @GetMapping("/{id}")
    public Result<Employee> getById(@PathVariable Long id) {
        log.info("根据Id查询员工信息...");

        Employee employee = employeeService.getById(id);

        return Result.success(employee);
    }

    ;
}
